//
//  NewCollectionViewController.swift
//  Microblog
//
//  Created by steaest on 15/8/2.
//  Copyright © 2015年 steaest. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class NewCollectionViewController: UICollectionViewController {
    
    //图片总数
    private let iamgeCount = 4
    
    //为什么是 UICollectionViewFlowLayout
    private let layout = FlowLayout()
    
    //? 没有 override，因为 collectionView 的指定的构造函数是带 layout 的
    init() {
        super.init(collectionViewLayout: layout)
    }
    
    required init?(coder aDecoder: NSCoder) {
        //下面一句代码的意思是本类禁止用SB开发,纯代码开发,考虑因素少,风险小
        //fatalError("init(coder:) has not been implemented")
        
        //本类允许用SB开发,适用于混合开发,需要测试
        super.init(coder: aDecoder)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.registerClass(NewfeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }

    // MARK: UICollectionViewDataSource
    //执行先后顺序 1.获取数据,确认有cell
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return 4
    }

    //3.获取每个索引对应的cell
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewfeatureCell
        
        cell.imageIndex = indexPath.item
        
        return cell
    }
    
    //collectionView代理方法
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        
        //indePath显示的消失的那个界面的索引
        //print(indexPath)
        
        //获取当前显示的path
        let path = collectionView.indexPathsForVisibleItems().last!
        
        //判断是否是末尾的indexPath
        if path.item == 3 {
        
            let cell = collectionView.cellForItemAtIndexPath(path) as! NewfeatureCell
            
            cell.startBtnAnimation()
        }
    }
}


//MARK:新特性的 cell
class NewfeatureCell: UICollectionViewCell {
    
    private var imageIndex: Int = 0 {
        didSet{
            iconView.image = UIImage(named: "new_feature_\(imageIndex+1)")
            
            //开始动画为什么会在这里
            //startBtnAnimation()
            
            btn.hidden = true
        }
    }

    //MARK:设置UI
    override init(frame: CGRect) {
        super.init(frame: frame)
        perpareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        //fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
        perpareUI()
    }
    
    //MARK:按钮动画
    private func startBtnAnimation() {
    
        btn.hidden = false
        
        btn.userInteractionEnabled = false
        
        btn.transform = CGAffineTransformMakeScale(0.5, 0.5)
        
        UIView.animateWithDuration(1.2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            
            //恢复默认形变
            self.btn.transform = CGAffineTransformIdentity
            
            }) { (_) -> Void in
                
            self.btn.userInteractionEnabled = true
        }
    }
    
    //MARK:按钮监听
    func startBtn() {
    
        NSNotificationCenter.defaultCenter().postNotificationName(WWRootViewControllerSwitchNotification, object: true)
    }
    
    //MARK:搭建界面
    private func perpareUI() {
        contentView.addSubview(iconView)
        contentView.addSubview(btn)
        
        //自动布局
        iconView.ff_Fill(contentView)
        
        btn.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: contentView, size: nil, offset: CGPointMake(0, -160))
    }
    
    //懒加载控件
    private lazy var iconView = UIImageView()
    private lazy var btn: UIButton = {
        
        let btn = UIButton()
        
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        btn.setTitle("开始体验", forState: UIControlState.Normal)
        
        btn.addTarget(self, action: "startBtn", forControlEvents: UIControlEvents.TouchUpInside)
        
        btn.sizeToFit()
        
        //事实上,btn会因为cell的复用,工作不正常
        btn.hidden = true
        
        return btn
        
        }()
}

//自定义流水式布局
private class FlowLayout: UICollectionViewFlowLayout {

    //2.如果还没有设置 layout 获取数量之后,准备cell之前调用一次
    //准备布局属性
    private  override func prepareLayout() {
        
        itemSize = collectionView!.bounds.size
        //print(collectionView)
        //设置间隙
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        
        //方向
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        //分页
        collectionView?.pagingEnabled = true
        
        //?
        collectionView?.showsHorizontalScrollIndicator = false
        
        //弹簧
        collectionView?.bounces = false
        
    }
}
